package dt.inlee.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;

/**
 * 从本地上传文件到远程共享目录或从远程共享目录下载文件
 * 
 * @author 陈燕波
 * @version 2010-12-2
 */
public class RemoteFileOperating {

	/**
	 * * Description: 从共享目录拷贝文件返回in流 *
	 * 
	 * @Version1.0 Sep 25, 2009 3:48:38 PM *
	 * @param remoteUrl
	 * 
	 */
	@SuppressWarnings("unused")
    public InputStream smbGet(String remoteUrl) {
		InputStream in = null;
		try {
			SmbFile remoteFile = new SmbFile(remoteUrl);

			if (remoteFile == null) {
				System.out.println("共享文件不存在");
				return null;
			}
			in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return in;
	}

	/**
	 * Description: 从本地上传文件到共享目录 *
	 * 
	 * @param remoteUrl
	 *            共享文件目录
	 * @param localFilePath
	 *            本地文件绝对路径
	 * 
	 */
	public void smbPut(String remoteUrl, String localFilePath, String fileName) {
		InputStream in = null;

		OutputStream out = null;
		try {
			File localFile = new File(localFilePath);

			SmbFile remoteFile = new SmbFile(remoteUrl + "/" + fileName);

			in = new BufferedInputStream(new FileInputStream(localFile));

			out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));

			byte[] buffer = new byte[1024];

			while (in.read(buffer) != -1) {

				out.write(buffer);

				buffer = new byte[1024];

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	/**
	 * Description: 从本地上传文件到共享目录 *
	 * 
	 * @param remoteUrl
	 *            远程共享文件目录
	 * @param in
	 *            文件流
	 * @param fileName
	 *            文件名
	 */
	public void smbPut(String remoteUrl, InputStream in, String fileName) {

		OutputStream out = null;
		try {

			SmbFile remoteFile = new SmbFile(remoteUrl + "/" + fileName);

			out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));

			byte[] buffer = new byte[1024];

			while (in.read(buffer) != -1) {

				out.write(buffer);

				buffer = new byte[1024];

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
}
